package com.grantheath.erebus.view 
{
	import com.grantheath.erebus.model.interfaces.IErebusURLProxy;
	import com.grantheath.erebus.model.enum.notifications.ErebusURLNotifications;
	import com.grantheath.erebus.model.enum.names.ErebusMediatorNames;
	import com.grantheath.erebus.model.enum.names.ErebusProxyNames;
	import com.grantheath.erebus.model.interfaces.IErebusSiteTreeProxy;

	import com.asual.swfaddress.SWFAddressEvent;
	import com.asual.swfaddress.SWFAddress;

	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.puremvc.as3.interfaces.INotification;

	/**
	 * @author grantheath
	 */
	public class ErebusURLMediator extends Mediator implements IMediator 
	{
		private var _useURLChangedEvent : Boolean;

		public function ErebusURLMediator()
		{
			super(ErebusMediatorNames.URL_MEDIATOR);
			
			_useURLChangedEvent = true;
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, onURLChange);
		}

		override public function listNotificationInterests() : Array
		{
			return [ErebusURLNotifications.SET_PAGE_TITLE, ErebusURLNotifications.SET_PAGE, ErebusURLNotifications.SET_URL, ErebusURLNotifications.SET_URL_WITH_HISTORY];
		}

		//NOTIFICATION HANDELERS
		override public function handleNotification(notification : INotification) : void
		{
			var notificationName : String = notification.getName();
			var url : String = notification.getBody() as String;
			
			if(notificationName == ErebusURLNotifications.SET_PAGE_TITLE) {
				SWFAddress.setTitle(url);
			} else if(notificationName == ErebusURLNotifications.SET_PAGE) {
				SWFAddress.setHistory(true);
				SWFAddress.setValue(url);
			} else if(notificationName == ErebusURLNotifications.SET_URL) {
				_useURLChangedEvent = false;
				SWFAddress.setHistory(false);
				SWFAddress.setValue(url);
				_useURLChangedEvent = true;
			} else if(notificationName == ErebusURLNotifications.SET_URL_WITH_HISTORY) {
				_useURLChangedEvent = false;
				SWFAddress.setHistory(true);
				SWFAddress.setValue(url);
				_useURLChangedEvent = true;
			}
		}

		//EVENT HANDELERS
		private function onURLChange(event : SWFAddressEvent) : void
		{
			var urlProxy : IErebusURLProxy = facade.retrieveProxy(ErebusProxyNames.URL_PROXY) as IErebusURLProxy;
			var newURL : String = SWFAddress.getValue();
			
			if(newURL != urlProxy.URL) {
				sendNotification(ErebusURLNotifications.URL_CHANGED, newURL);
				if(_useURLChangedEvent) {
					var siteTreeProxy : IErebusSiteTreeProxy = facade.retrieveProxy(ErebusProxyNames.SITE_TREE_PROXY) as IErebusSiteTreeProxy;
					
					if(siteTreeProxy.isTransitioning) {
						siteTreeProxy.interuptTransition = true;
						urlProxy.URLNoTransition = newURL;
					} else {
						urlProxy.URL = newURL;
					}
				}
			}
		}

		//GETTERS AND SETTERS
		override public function getMediatorName() : String
		{
			return NAME;
		}
	}
}
